﻿// --------------------------------
// <copyright file="RemoteGamepad.cs" company="Faculty of Information Technology, Czech Technical University in Prague">
//     This document is shared by Microsoft Public License (MS-PL)
//     For further details please see http://msdn.microsoft.com/en-us/library/ff648068.aspx or license.txt.
// </copyright>
// <author>Lukáš Molnár</author>

// <email>molnaluk@fit.cvut.cz</email>

// <date>22. 1. 2012 12:47:06</date>

// <summary>
//
// </summary>
// --------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using LProject.Phone.Net;
using FITClub.Util;

namespace FITClub.Episode1.Controller
{
    public enum VirtualGamepadButtons : byte
    {
        Up = 0,
        Left,
        Down,
        Right,
        Attack,
        Defence
    }

    public class RemoteGamepadReceiver : IDisposable
    {
        private struct RemoteGamepad
        {
            public VirtualGamepadState state;
            public DateTime lastPacketDate;
            public int sequence;

            public RemoteGamepad(VirtualGamepadState initialState)
            {
                state = initialState;
                lastPacketDate = DateTime.Now;
                sequence = -1;
            }

            public void Update(byte state, int seq)
            {
                if (seq > sequence)
                {
                    this.state = new VirtualGamepadState(new byte[] { state });
                    sequence = seq;
                    lastPacketDate = DateTime.Now;
                }                
            }

            public void UpdateIdle()
            {
                TimeSpan twithoutPacket = DateTime.Now - this.lastPacketDate;
                if (twithoutPacket.TotalMilliseconds > 100)
                {
                    this.state = VirtualGamepadState.Default;
                }
            }
        }

        private struct QueueItem
        {
            public int sequence;
            public byte state;
            public byte sender;
        }

        private RemoteGamepad[] playersGamepad;

        Queue<QueueItem> incomingStates;
        SpinLock spin;
        

        public RemoteGamepadReceiver(MulticastClient client)
        {
            this.spin = new SpinLock(100);
            
            this.client = client;
            if (client.InClub == false)
            {
                throw new InvalidOperationException("Client must be in the club");
            }
            this.SyncRoot = new object();
            this.client.AddPacketProcessor(this.ProcessPacket);
            this.playersGamepad = new RemoteGamepad[16];

            for (int i = 0; i < playersGamepad.Length; i++)
            {
                playersGamepad[i] = new RemoteGamepad(VirtualGamepadState.Default);
            }

            this.incomingStates = new Queue<QueueItem>();


            //foreach (var item in this.client.Presence)
            //{
            //    if (item.ID != this.client.MyID)
            //    {
            //        this.playersGamepad.Add(item.ID, VirtualGamepadState.Default);
            //    }
            //}
        }

        MulticastClient client;
        private volatile bool locked;

        public object SyncRoot { get; private set; }

        /// <summary>
        /// Provides copy of player's gamepad state.
        /// </summary>
        /// <param name="playerIndex"></param>
        /// <returns></returns>
        public VirtualGamepadState GetState(byte playerIndex)
        {
            return this.playersGamepad[playerIndex].state;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="packet">Packet to preocess</param>
        /// <returns>true - if the packet was processed</returns>
        private bool ProcessPacket(IMulticastPacket packet)
        {
                switch (packet.Type)
                {
                    case PacketType.ControllerState:
                        spin.Lock();
                        incomingStates.Enqueue(new QueueItem()
                        {
                            sender = packet.SenderID,
                            sequence = packet.GetInt32(RawPacket.HeaderLength + 1),
                            state = packet.Data[RawPacket.HeaderLength]
                        });
                        spin.Unlock();
                        return true;
                }
#if DEBUG
               System.Diagnostics.Debig.WriteLine("{0} not processed", packet.Type);
#endif
                return false;
        }

        private void UpdateSequence(int seq, byte state, byte sender)
        {
            playersGamepad[sender].Update(state, seq);
        }

        public void Update()
        {
            while (this.incomingStates.Count > 0)
            {
                QueueItem qi = this.incomingStates.Dequeue();
                UpdateSequence(qi.sequence, qi.state, qi.sender);
            }
            foreach (var item in this.playersGamepad)
            {
                item.UpdateIdle();
            }
        }

        public void Dispose()
        {
            this.client.RemovePacketProcessor(this.ProcessPacket);
            //using (var fs = new StreamWriter(File.OpenWrite("all_sequences.log")))
            //{
            //    foreach (var item in sequences)
            //    {
            //        fs.WriteLine(item);
            //    }
            //}
            //sequences.Sort();
            //int pseq = sequences[0];
            //using (var fs = new StreamWriter(File.OpenWrite("missing_sequences.log")))
            //{
            //    for (int i = 1; i < sequences.Count; i++)
            //    {
            //        if (pseq + 1 != sequences[i] && sequences[i] != pseq)
            //        {
            //            fs.WriteLine("{0} {1}", pseq, sequences[i]);
            //        }
            //        pseq = sequences[i];
            //    }
            //}
        }
    }
}